package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.Document;

import main.Client;

public class TerminalPanel extends JPanel {
	private static final long serialVersionUID = -7925839789600145504L;
	
	private JTextArea textArea;
	private JTextField inputField;
	private JButton btnSend;
	
	private Client client = null;
	
	public int index = 0;
	public String tabTitle = "";
	private JScrollPane spane;
	
	public TerminalPanel()
	{
		super();
	
		textArea = new JTextArea();
		textArea.setBackground(Color.BLACK);
		textArea.setForeground(Color.GREEN);
		textArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
		textArea.setEditable(false);
		textArea.append(" ");
		
		inputField = new JTextField();
		inputField.setBackground(Color.BLACK);
		inputField.setForeground(Color.GREEN);
		inputField.setCaretColor(Color.GREEN);
		inputField.setFont(new Font("Monospaced", Font.PLAIN, 12));
		
		btnSend = new JButton("Send");
		
		this.setLayout(new BorderLayout());
		spane = new JScrollPane(textArea);
		this.add(spane, BorderLayout.CENTER);
		JPanel bottomPanel = new JPanel();
		bottomPanel.setLayout(new BorderLayout());
		bottomPanel.add(inputField, BorderLayout.CENTER);
		bottomPanel.add(btnSend, BorderLayout.EAST);
		this.add(bottomPanel, BorderLayout.SOUTH);
		
		inputField.setEnabled(false);
		btnSend.setEnabled(false);
	}

	public void setInputEnabled(boolean e)
	{
		inputField.setEnabled(e);
		btnSend.setEnabled(e);
	}
	
	public Client getClient() {
		return client;
	}
	
	public String getInputText()
	{
		return inputField.getText();
	}
	
	public void clearInputText()
	{
		inputField.setText("");
	}

	public void setClient(Client client) {
		this.client = client;
		btnSend.addActionListener(client);
		inputField.addKeyListener(client);
	}
	
	synchronized public void appendLine(String txt)
	{
		if(txt.length() == 0) return;
		textArea.append(txt);
		textArea.scrollRectToVisible(new Rectangle(0,textArea.getHeight()-2,1,1));
		
		Document d = textArea.getDocument();
		textArea.select(d.getLength(), d.getLength());
	}
}
